package com.qf.java2105.huangchuang.hotel.controller.user;

import com.alibaba.druid.util.StringUtils;
import com.qf.java2105.huangchuang.hotel.constant.MessageConstant;
import com.qf.java2105.huangchuang.hotel.constant.ResponseMessageConstant;
import com.qf.java2105.huangchuang.hotel.controller.BaseServlet;
import com.qf.java2105.huangchuang.hotel.entity.ResultVO;
import com.qf.java2105.huangchuang.hotel.factory.BeanFactory;
import com.qf.java2105.huangchuang.hotel.pojo.User;
import com.qf.java2105.huangchuang.hotel.service.IUserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录控制
 * @author hcvg
 * @version v1.0
 * @date 2021/09/15
 **/
@WebServlet("/user")
public class UserController extends BaseServlet {

    private IUserService userService = (IUserService) BeanFactory.getBean("userService");

    String login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        String validate = request.getParameter("validate");
        String validateCode = (String) request.getSession().getAttribute("validateCode");

        ResultVO<User> resultVO = null;
        // 用户名不能为空
        if (StringUtils.isEmpty(userName)){
            return "<script>location.href = \"/login.jsp\"</script>";
        }
        //验证码不能为空
//        if (StringUtils.isEmpty(validate)){
//            return "<script>alert('" + MessageConstant.NO_VALIDATE_CODE + "'); location.href = \"/index.jsp\"</script>";
//        }
//        //验证码不能出错
//        if (!validate.equalsIgnoreCase(validateCode)){
//            return "<script>alert('" + MessageConstant.WRONG_VALIDATE_CODE + "'); location.href = \"/index.jsp\"</script>";
//        }

        resultVO = userService.login(userName);
        if (resultVO.getSuccess()){
            request.setAttribute("user", resultVO.getData());
            request.getSession().setAttribute("userTemp", resultVO.getData());
            if (resultVO.getData().getPassword().equals(password)){
                if (1 == resultVO.getData().getIsAdmin()){
                    return ResponseMessageConstant.PREFIX_FORWARD + request.getContextPath() + "/choosePageTwo.jsp";
                }else {
                    return ResponseMessageConstant.PREFIX_FORWARD + request.getContextPath() + "/front/index.jsp";
                }
            }
            return "<script>alert('" + MessageConstant.QUERY_USER_FAILED + "'); location.href = \"/login.jsp\"</script>";
        }
        return null;
    }


}
